package com.example.elysiumease;

import com.example.elysiumease.mapper.UserMapper;
import com.example.elysiumease.model.User;
import com.example.elysiumease.model.User.Role;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@Transactional // 测试后自动回滚
@Commit
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    // 测试用户基础数据
    private User createTestUser() {
        return new User() {{
            setUsername("test_" + UUID.randomUUID().toString().substring(0, 8));
            setPasswordHash("secure_hash");
            setAngelName("Test Angel");
            setRole(Role.OPERATOR);
            setDepartment("Testing Dept");
            setLastLogin(LocalDateTime.now());
        }};
    }


    @Test
    void testInsertUser() {
        User user = createTestUser();

        // 测试插入操作
        int result = userMapper.insert(user);
        assertEquals(1, result);
        assertNotNull(user.getUserId(), "插入后应生成用户ID");

        // 验证数据实际存储
        User dbUser = userMapper.selectById(user.getUserId());
        assertNotNull(dbUser, "应能查询到新插入的用户");
        assertEquals(user.getUsername(), dbUser.getUsername(), "用户名应一致");
    }

    @Test
    void testUpdateUser() {
        // 先插入测试用户
        User user = createTestUser();
        userMapper.insert(user);

        // 修改用户信息
        String newDepartment = "Updated Dept";
        user.setDepartment(newDepartment);
        int updateResult = userMapper.update(user);

        assertEquals(1, updateResult, "应成功更新1条记录");

        // 验证更新结果
        User updatedUser = userMapper.selectById(user.getUserId());
        assertEquals(newDepartment, updatedUser.getDepartment(), "部门信息应已更新");
    }

//    @Test
//    void testDeleteUser() {
//        // 插入测试用户
//        User user = createTestUser();
//        userMapper.insert(user);
//
//        // 执行删除
//        int deleteResult = userMapper.deleteById(user.getUserId());
//        assertEquals(1, deleteResult, "应成功删除1条记录");
//
//        // 验证删除结果
//        User deletedUser = userMapper.selectById(user.getUserId());
//        assertNull(deletedUser, "删除后查询应返回null");
//    }

    @Test
    void testSelectUser() {
        // 插入测试用户
        User user = createTestUser();
        userMapper.insert(user);

        // 执行查询
        User dbUser = userMapper.selectById(user.getUserId());

        // 验证查询结果
        assertAll("用户字段验证",
                () -> assertEquals(user.getUsername(), dbUser.getUsername()),
                () -> assertEquals(user.getRole(), dbUser.getRole()),
                () -> assertNotNull(dbUser.getCreatedAt(), "创建时间应自动生成")
        );
    }
}